/**
 * Copyright 2015 jianglibo@gmail.com
 *
 */
package com.m3958.logcollector.whl;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

import org.junit.Before;

import com.m3958.logcollector.config.AppConfig;

/**
 * @author jianglibo@gmail.com
 *         2016年1月11日
 *
 */
public abstract class WhlBase {

    public Path fixturePath = Paths.get("fixtures", "out", "whl");
    
    public int fnuFilenameLengthLimit = 10;

    @Before
    public void b() throws IOException {
        if (!Files.exists(fixturePath)) {
            Files.createDirectories(fixturePath);
        }
        
        Files.walk(fixturePath).forEach(p -> {
            try {
                Files.delete(p);
            } catch (Exception e) {
            }
        });
    }

    protected void createDemoFiles(int dones, int undones) throws IOException {
        FileNameUtils fnu = new FileNameUtils(fixturePath, fnuFilenameLengthLimit);
        PrintWriter pw = fnu.switchWriter(null); // should create file i00
        int total = dones + undones - 1;
        for (int i = 0; i < total; i++) {
            pw = fnu.switchWriter(pw);
        }
        pw.close();
        Path p = fnu.getLastFilePathFromLastFileNumber();
        Files.createFile(p.getParent().resolve(p.getFileName() + ".done"));

        String[] ss = fnu.listSortedFileName();

        String[] undone = Arrays.copyOfRange(ss, dones, total + 1);

        for (String s : undone) {
            Files.delete(fnu.getWorkingDir().resolve(s + ".done"));
        }
        assertThat(fnu.getLastFileNumber(), is(Long.valueOf(dones + undones - 1)));
        assertThat(undone.length, is(undones));

    }

    protected AppConfig getAppConfig() {
        AppConfig appConfig = mock(AppConfig.class);
        when(appConfig.getWhlRootPath()).thenReturn(Paths.get("fixtures", "out", "whl"));
        return appConfig;
    }

}
